package org.anyline.simple.postgres;

import org.anyline.adapter.KeyAdapter;
import org.anyline.data.jdbc.adapter.JDBCAdapter;
import org.anyline.data.param.ConfigStore;
import org.anyline.data.param.init.DefaultConfigStore;
import org.anyline.entity.DataRow;
import org.anyline.entity.DataSet;
import org.anyline.metadata.Constraint;
import org.anyline.metadata.Table;
import org.anyline.service.AnylineService;
import org.anyline.util.BasicUtil;
import org.anyline.util.BeanUtil;
import org.anyline.util.ConfigTable;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;



@SpringBootApplication
public class PostgresApplication {
    private static  AnylineService service;

    public static void main(String[] args) throws Exception {
        SpringApplication application = new SpringApplication(PostgresApplication.class);
        ConfigurableApplicationContext ctx = application.run(args);
        service = (AnylineService) ctx.getBean("anyline.service");
        DataRow.DEFAULT_KEY_CASE = KeyAdapter.KEY_CASE.SRC;
        DataRow.DEFAULT_PRIMARY_KEY = "id";
        //init();
       // array();
       // dml();

       // metadata();
        //type();
       // override();
        DataRow row =new DataRow();
        row.setTable("crm_user");
        row.put("ID","1");
        ConfigTable.IS_AUTO_CHECK_METADATA = true;
        service.querys("crm_user", row);

        System.exit(0);
    }
    public static void override() throws Exception{
        Table table = service.metadata().table("CRM_USER");
        if(null != table){
            service.ddl().drop(table);
        }
        table = new Table("CRM_USER");
        table.addColumn("ID", "bigint").primary(true).autoIncrement(true);
        table.addColumn("CODE", "VARCHAR(10)");
        table.addColumn("NAME","VARCHAR(10)");
        service.ddl().create(table);
        //唯一索引
        Constraint u_code = new Constraint<>(table, "u_code").setType(Constraint.TYPE.UNIQUE).addColumn("CODE");
        service.ddl().add(u_code);

        DataSet set = new DataSet();
        for(int i=0; i<10; i++){
            DataRow row = new DataRow();
            row.put("CODE", "C"+i);
            row.put("NAME", "张三"+i);
            set.add(row);
        }
        service.insert("CRM_USER", set);
        set = new DataSet();
        for(int i=0; i<3; i++){
            DataRow row = new DataRow();
            row.put("CODE", "C"+i);
            row.put("NAME", "王五"+i);
            set.add(row);
        }
        //根据CODE判断 重复则覆盖
        ConfigStore configs = new DefaultConfigStore();
        configs.override(true, "CODE");
        service.insert("CRM_USER", set, configs);
        set = new DataSet();
        for(int i=3; i<6; i++){
            DataRow row = new DataRow();
            row.put("CODE", "C"+i);
            row.put("NAME", "赵六"+i);
            set.add(row);
        }
        //根据唯一索引判断 重复则覆盖
        configs.override(true, u_code);
        service.insert("CRM_USER", set, configs);
        set = new DataSet();
        for(int i=6; i<9; i++){
            DataRow row = new DataRow();
            row.put("CODE", "C"+i);
            row.put("NAME", "不覆盖"+i);
            set.add(row);
        }
        //根据唯一索引判断 重复则忽略
        configs.override(false, u_code);
        service.insert("CRM_USER", set, configs);
    }
    public static void array(){
        Employee employee = new Employee();
        List<Integer> types = new ArrayList<>();
        types.add(1);
        types.add(2);
        employee.setTypes(types);
        employee.setDouble_array(new double[]{111,333.22});
        service.save(employee);
        DataSet set = service.querys("HR_EMPLOYEE");
    }
    public static void init() throws Exception{

        ConfigTable.IS_AUTO_CHECK_METADATA = true;
        //职员表
        org.anyline.metadata.Table table = service.metadata().table("HR_EMPLOYEE");
        if(null != table){
            service.ddl().drop(table);
        }
        table = new org.anyline.metadata.Table("HR_EMPLOYEE");
        //注意以下数据类型
        table.addColumn("ID"            , "BIGINT"       ).setComment("主键").autoIncrement(true).primary(true);
        table.addColumn("NAME"          , "varchar(50)"  ).setComment("姓名")     ; // String          : nm
        table.addColumn("CODE"          , "varchar(50)"  ).setComment("工号")     ; // String          : workCode
        table.addColumn("BIRTHDAY"      , "DATE"         ).setComment("出生日期")  ; // Date            : birthday
        table.addColumn("JOIN_YMD"      , "varchar(10)"  ).setComment("入职日期")  ; // String          : joinYmd
        table.addColumn("SALARY"        , "float(10,2)"  ).setComment("工资")     ; // float           : salary
        table.addColumn("REMARK"        , "blob"         ).setComment("备注")     ; // byte[]          : remark
        table.addColumn("DESCRIPTION"   , "blob"         ).setComment("详细信息")  ; // String          : description
        table.addColumn("DEPARTMENT"    , "json"         ).setComment("部门")     ; // Department      : department
        table.addColumn("POSTS"         , "json"         ).setComment("职务s")    ; // Map<String,Post>: posts
        table.addColumn("EXPERIENCES"   , "json"         ).setComment("工作经历")  ; // List<Experience>: experiences
        table.addColumn("TITLES"        , "json"         ).setComment("头衔s")    ; // List<String>    : titles
        table.addColumn("LABELS"        , "json"         ).setComment("标签s")    ; // String[]        : labels
        table.addColumn("SCORES"        , "json"         ).setComment("成绩s")    ; // int[]           : scores
        table.addColumn("CTITLES"       , "varchar(255)" ).setComment("头衔s")    ; // List<String>    : ctitles
        table.addColumn("CLABELS"       , "varchar(255)" ).setComment("标签s")    ; // String[]        : clabels
        table.addColumn("CSCORES"       , "varchar(255)" ).setComment("成绩s")    ; // int[]           : cscores
        table.addColumn("OTHER"         , "json"         ).setComment("其他信息")  ; // Object          : other
        table.addColumn("MAP"           , "json"         ).setComment("其他信息")  ; // Map             : map
        table.addColumn("WORK_LOCATION" , "point"        ).setComment("工作定位")  ; // Double[]        : workLocation
        table.addColumn("HOME_LOCATION" , "point"        ).setComment("住址定准")  ; // Point           : homeLocation*/
        table.addColumn("LOCAL_TIME"    , "time");
        table.addColumn("TYPE_ARRAY"    , "text[]"); //pg支持
        table.addColumn("DOUBLE_ARRAY"  , "int[]"); //pg支持
        table.addColumn("DATA_STATUS"   , "int"          ).setComment("状态").setDefaultValue(1);
        //注意SQL Server中一个表只能有一列TIMESTAMP
        table.addColumn("CREATE_TIME"   , "TIMESTAMP"    ).setDefaultValue(JDBCAdapter.SQL_BUILD_IN_VALUE.CURRENT_DATETIME);
        table.addColumn("REG_TIME"      , "TIMESTAMP"    ).setDefaultValue(JDBCAdapter.SQL_BUILD_IN_VALUE.CURRENT_DATETIME);
        service.ddl().create(table);


        table = service.metadata().table("tb_user");
        if(null != table){
            service.ddl().drop(table);
        }
        table = new Table("tb_user");
        table.addColumn("name", "varchar(32)");
        table.addColumn("id", "varchar(32)");
        table.addColumn("remark", "varchar(32)");
        service.ddl().create(table);
    }
    public static void dml(){
        //序列查询

        BigDecimal next = service.sequence("SIMPLE_SEQ");
        DataRow nexts = service.sequences("SIMPLE_SEQ", "SIMPLE_SEQ2");
        BigDecimal cur = service.sequence(false,"SIMPLE_SEQ");
        DataRow curs = service.sequences(false, "SIMPLE_SEQ", "SIMPLE_SEQ2");

        DataRow row = new DataRow();
        row.put("name", "张三");
        row.put("id", BasicUtil.getRandomString(32));
        service.insert("tb_user", row);
        System.out.println(row);
    }
    public static void metadata(){

        List<String> mts = service.columns("tb_user");
        System.out.println(BeanUtil.object2json(mts));
        //DataSet set = service.querys("tb_user(email)",0,1);
        //System.out.println(set);

        List<String> tables = service.tables();
        System.out.println(tables);
        tables = service.tables(1);
        System.out.println(tables);
        tables = service.tables("ts_%",1);
        System.out.println(tables);
        tables = service.tables("public","ts_%",1);
        System.out.println(tables);
    }
    public static void type(){

        DataRow user = new DataRow();
        user.put("id", UUID.randomUUID());
        user.put("created_time", System.currentTimeMillis());
        user.put("first_name", BasicUtil.getRandomString(10));
        user.put("t1", new Date())      ; //date
        user.put("t2", new Date())      ; //timestamp
        user.put("t3", new Date())      ; //time
        user.put("t4", new Date())      ; //timestamptz
        user.put("t5", new Date())      ; //timetz
        user.put("t6", new Date())      ; //text 会执行 DateUtil.format(date);

        //日期类型会转换失败会换成null
        user.put("t1", "")              ; //date
        user.put("t2", "")              ; //timestamp
        user.put("t3", "")              ; //time
        user.put("t4", "")              ; //timestamptz
        user.put("t5", "")              ; //timetz
        //string类型不变
        user.put("t6", "")              ; //text 会执行 DateUtil.format(date);


        user.put("+t7", "100")          ; //numeric 如果传入“”会转换成null
        user.put("t8", "{\"a\":1}")     ; //json
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><config></config>";
        user.put("t9",xml)              ; //xml
        user.put("c1", 1)               ; //bit
        user.put("c2", true)            ; //bool
        user.put("c3","(1,1),(1,1)")    ; //box
        user.put("c4", new byte[0])     ; //bytea
        user.put("c5", "abc")           ; //char
        user.put("c6","192.168.0.1")    ; //cidr
        user.put("c7","1,1,5")          ; //circle

        user.put("v1",null)             ; //在执行插入更新时忽略
        user.put("v2", "")              ; //在执行插入更新时忽略
        user.put("+v3", null)           ; //强制参与更新和插入
        user.setIsNew(true);
        //t7 列的类型是numeric直接save会报错
        try {
            service.save("tb_user", user);
        }catch (Exception e){
            e.printStackTrace();
        }
        //保存前需要检测数据类型
        ConfigTable.IS_AUTO_CHECK_METADATA = true;
        service.save("tb_user", user);
        //只更新t6 t7
        service.update("tb_user",user,"t6","t7");
        //t6强制更新 其他按默认情况
        service.update("tb_user",user,"+t6");
        //只更新值有变化的列
        service.update("tb_user",user);
        //System.out.println(BeanUtil.object2json(service.metadatas("tb_user")));

    }
}
